<template>
  <!--    @longpress="longPressItem"-->

  <view
    class="item-container"
    :class="{ dragging: isDragging }"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @longpress="longPressItem"
    @touchcancel="handleTouchEnd"
    :style="{ transform: `translateY(${translateY}rpx)`, transition: transition }"
  >
    <view class="item-info">
      <view class="item-name-section">
        <text class="item-name">{{ item.name || `物料${item.lastReplacementDate}` }}</text>
        <text class="item-cycle">更换周期: {{ item.replacementCycle }}个月</text>
      </view>
      <view class="item-countdown">
        <text :style="{ color: statusColor }">{{ remainingTime }}</text>
      </view>
      <view class="item-actions">
        <uni-icons type="refreshempty" size="35" @click="replaceItem"></uni-icons>
      </view>
    </view>

    <!-- 删除区域 -->
    <view
      class="delete-area"
      v-if="showDeleteArea"
      :style="{ height: deleteAreaHeight + 'rpx' }"
    >
      <text class="delete-text">松手删除</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useItemStore } from '@/stores/modules/item'

const props = defineProps<{
  item: any
}>()

const emit = defineEmits<{
  (e: 'delete', id: string): void
  (e: 'move', id: string, direction: 'up' | 'down'): void
  (e: 'calendarReminder', item: any): void
  (e: 'edit', item: any): void
}>()

const itemStore = useItemStore()

// 状态
const translateY = ref(0)
const startY = ref(0)
const currentY = ref(0)
const isDragging = ref(false)
const showDeleteArea = ref(false)
const deleteAreaHeight = ref(0)
const transition = ref('none')

// 计算属性
const remainingTime = computed(() => {
  const { months, days, remainingDays } = itemStore.calculateRemainingTime(props.item)
  // return `${months}月${days}天`
  return `${remainingDays}天`
})

const statusColor = computed(() => {
  const remainingDays = itemStore.calculateRemainingDays(props.item)
  if (remainingDays <= 0) {
    return '#ff4d4f' // 过期红色
  } else if (remainingDays <= 30) {
    return '#ffa000' // 即将过期橙色
  } else {
    return '#27ba9b' // 正常绿色
  }
})

// 事件处理
const handleTouchStart = (e: TouchEvent) => {
  startY.value = e.touches[0].clientY
  currentY.value = startY.value
  isDragging.value = true
  transition.value = 'none'
  showDeleteArea.value = false
  deleteAreaHeight.value = 0
}

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return

  currentY.value = e.touches[0].clientY
  translateY.value = currentY.value - startY.value

  // 检查是否拖动到屏幕底部20%区域
  const windowHeight = uni.getSystemInfoSync().windowHeight
  const bottomThreshold = windowHeight * 0.8

  if (currentY.value > bottomThreshold) {
    showDeleteArea.value = true
    deleteAreaHeight.value = 60
  } else {
    showDeleteArea.value = false
    deleteAreaHeight.value = 0
  }

  // 阻止页面滚动
  e.preventDefault()
}

const handleTouchEnd = () => {
  // 清除延时器
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value)
    longPressTimer.value = null
  }
  if (!isDragging.value) return

  isDragging.value = false
  transition.value = 'transform 0.3s'

  // 检查是否在删除区域
  const windowHeight = uni.getSystemInfoSync().windowHeight
  const bottomThreshold = windowHeight * 0.8

  if (currentY.value > bottomThreshold) {
    // 执行删除
    emit('delete', props.item.id)
  } else {
    // 检查是否左右滑动进行排序
    const deltaX = currentY.value - startY.value
    if (Math.abs(deltaX) > 50) {
      if (deltaX > 0) {
        emit('move', props.item.id, 'down')
      } else {
        emit('move', props.item.id, 'up')
      }
    }
  }

  // 重置位置
  setTimeout(() => {
    translateY.value = 0
    showDeleteArea.value = false
    deleteAreaHeight.value = 0
  }, 300)
}
const longPressTimer = ref(null) // 长按计时器
const longPressItem = () => {
  console.log('longPressItem')
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value)
  }
  // @ts-ignore 设置长按计时器
  longPressTimer.value = setTimeout(() => {
    handleLongPressComplete()
  }, 1000)

}
// 长按完成，进入编辑模式
const handleLongPressComplete = () => {
  console.log('长按2秒完成，进入编辑模式')
  // #ifdef APP-PLUS
  uni.vibrateShort({
    success: function () {
      console.log('触发手机震动');
    }
  });
  // #endif
  editItem()
}
const editItem = () => {
  console.log(`editItem itemId :${props.item.id}`)
  emit('edit', props.item)
}
// 更换物料
const replaceItem = () => {
  itemStore.replaceItem(props.item.id)
  uni.showToast({
    title: '更换成功',
    icon: 'success',
  })
  // 触发日历提醒
  emit('calendarReminder', props.item)
}
</script>

<style lang="scss" scoped>
.item-container {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 15rpx;
  margin-bottom: 10rpx;
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: transform 0.2s, box-shadow 0.2s;
  font-size: 30rpx;

  &.dragging {
    box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
    z-index: 100;
  }
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx 0 0;
}

.item-name-section {
  flex: 5;
  display: flex;
  flex-direction: column;
  padding: 0 20rpx;

  .item-name {
    font-size: 40rpx;
    font-weight: 500;
    margin-bottom: 5rpx;
  }

  .item-cycle {
    font-size: 30rpx;
    color: #999999;
  }
}

.item-countdown {
  flex: 3;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
}

.item-actions {
  flex: 2;
  display: flex;
  justify-content: flex-end;

  .iconfont {
    font-size: 30rpx;
    color: #27ba9b;
  }
}

.delete-area {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ff4d4f;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0 0 10rpx 10rpx;

  .delete-text {
    color: #ffffff;
    font-size: 50rpx;
    height: 100rpx;
    text-align: center;
    line-height: 100rpx;
  }
}
</style>